package com.enki.cigarettes.controller;

import com.enki.cigarettes.controller.vo.request.CartRequestVo;
import com.enki.cigarettes.controller.vo.response.CartResponseVo;
import com.enki.cigarettes.entity.*;
import com.enki.cigarettes.enums.ProductEnums;
import com.enki.cigarettes.handler.Response;
import com.enki.cigarettes.repository.*;
import com.enki.cigarettes.statics.StaticKeys;
import com.enki.cigarettes.utils.PrimaryKey;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author WCS.Wang
 * @version V1.0
 * @Package com.enki.cigarettes.controller
 * @Name e-cigarettes-shop-api-module
 * @Description: TODO 购物车逻辑层
 * @date 2019-07-19
 */
@RestController
@RequestMapping("/api/carts")
@Slf4j
public class CartController {

    @Autowired
    CartTRepository cartTRepository;
    @Autowired
    ProductSkuTRepository productSkuTRepository;
    @Autowired
    ProductTRepository productTRepository;
    @Autowired
    ProductSkuInventoryTRepository productSkuInventoryTRepository;
    @Autowired
    CouponTRepository couponTRepository;
    @Autowired
    ProductFollowTRepository productFollowTRepository;
    @Autowired
    UserTRepository userTRepository;
    @Autowired
    CategoryAttrValTRepository categoryAttrValTRepository;
    @Autowired
    CategoryAttrTRepository categoryAttrTRepository;


    @ApiOperation(value = "保存购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "long", required = true),
            @ApiImplicitParam(name = "colorSku", value = "颜色sku", dataType = "String"),
            @ApiImplicitParam(name = "sizeSku", value = "尺码sku", dataType = "String"),
            @ApiImplicitParam(name = "quantity", value = "数量", dataType = "int", required = true)
    })
    @PostMapping
    public Object saveCart(@RequestBody CartRequestVo item, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            ProductT productBean = productTRepository.findOneByIdAndStatus(item.getProductId(), ProductEnums.ProductStatus.ONTHSHELF.getType());
            if (productBean == null) {
                return Response.notFound_404("不存在的商品信息");
            }
            ProductSkuT productSkuBean = null;
            if (StringUtils.isNotBlank(item.getColorSku()) && StringUtils.isNotBlank(item.getSizeSku())) {
                String skuCode_1 = item.getColorSku() + StaticKeys.PRODUCT_SKU_SPLIT + item.getSizeSku();
                productSkuBean = productSkuTRepository.findOneByProductTIdAndSkuCodeAndStatus(item.getProductId(), skuCode_1, ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
                if (productSkuBean == null) {
                    String skuCode_2 = item.getSizeSku() + StaticKeys.PRODUCT_SKU_SPLIT + item.getColorSku();
                    productSkuBean = productSkuTRepository.findOneByProductTIdAndSkuCodeAndStatus(item.getProductId(), skuCode_2, ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
                }
            } else if (StringUtils.isNotBlank(item.getColorSku())) {
                String skuCode_1 = item.getColorSku() + StaticKeys.PRODUCT_SKU_SPLIT;
                productSkuBean = productSkuTRepository.findOneByProductTIdAndSkuCodeAndStatus(item.getProductId(), skuCode_1, ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
            }
            CartT cartBean = cartTRepository.findOneByUserTIdAndProductTIdAndProductSkuTId(sessionId.toString(), item.getProductId(), productSkuBean.getId());
            if (cartBean != null) {
                int newQuantity = cartBean.getQuantity() + item.getQuantity();
                cartBean.setQuantity(newQuantity);
                cartTRepository.save(cartBean);
                return Response.success(cartBean.getId(), StaticKeys.SUCCESS);
            } else {
                CartT bean = new CartT();
                bean.setId(PrimaryKey.get().toString());
                bean.setUserTId(sessionId.toString());
                bean.setProductTId(item.getProductId());
                bean.setProductSkuTId(productSkuBean.getId());
                bean.setQuantity(item.getQuantity());
                bean.setDealPrice(productSkuBean.getSalePrice());
                bean.setStoreTId(productBean.getStoreTId());
                bean.setCreateTime(new Date());
                cartTRepository.save(bean);
                return Response.success(bean.getId(), StaticKeys.SUCCESS);
            }
        } catch (Exception e) {
            log.error("保存购物车失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，保存购物车失败");
        }
    }

    @ApiOperation(value = "立即购买")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "long", required = true),
            @ApiImplicitParam(name = "colorSku", value = "颜色sku", dataType = "String"),
            @ApiImplicitParam(name = "sizeSku", value = "尺码sku", dataType = "String"),
            @ApiImplicitParam(name = "quantity", value = "数量", dataType = "int", required = true)
    })
    @PostMapping(value = "/buy")
    public Object buyNow(@RequestBody CartRequestVo item, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            ProductT productBean = productTRepository.findOneByIdAndStatus(item.getProductId(), ProductEnums.ProductStatus.ONTHSHELF.getType());
            if (productBean == null) {
                return Response.notFound_404("不存在的商品信息");
            }
            ProductSkuT productSkuBean = null;
            if (StringUtils.isNotBlank(item.getColorSku()) && StringUtils.isNotBlank(item.getSizeSku())) {
                String skuCode_1 = item.getColorSku() + StaticKeys.PRODUCT_SKU_SPLIT + item.getSizeSku();
                productSkuBean = productSkuTRepository.findOneByProductTIdAndSkuCodeAndStatus(item.getProductId(), skuCode_1, ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
                if (productSkuBean == null) {
                    String skuCode_2 = item.getSizeSku() + StaticKeys.PRODUCT_SKU_SPLIT + item.getColorSku();
                    productSkuBean = productSkuTRepository.findOneByProductTIdAndSkuCodeAndStatus(item.getProductId(), skuCode_2, ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
                }
            } else if (StringUtils.isNotBlank(item.getColorSku())) {
                String skuCode_1 = item.getColorSku() + StaticKeys.PRODUCT_SKU_SPLIT;
                productSkuBean = productSkuTRepository.findOneByProductTIdAndSkuCodeAndStatus(item.getProductId(), skuCode_1, ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
            }
            CartT cartBean = cartTRepository.findOneByUserTIdAndProductTIdAndProductSkuTId(sessionId.toString(), item.getProductId(), productSkuBean.getId());
            if (cartBean != null) {
                cartBean.setQuantity(item.getQuantity());
                cartTRepository.save(cartBean);
                return Response.success(cartBean.getId(), StaticKeys.SUCCESS);
            } else {
                CartT bean = new CartT();
                bean.setId(PrimaryKey.get().toString());
                bean.setUserTId(sessionId.toString());
                bean.setProductTId(item.getProductId());
                bean.setProductSkuTId(productSkuBean.getId());
                bean.setQuantity(item.getQuantity());
                bean.setDealPrice(productSkuBean.getSalePrice());
                bean.setStoreTId(productBean.getStoreTId());
                bean.setCreateTime(new Date());
                cartTRepository.save(bean);
                return Response.success(bean.getId(), StaticKeys.SUCCESS);
            }
        } catch (Exception e) {
            log.error("保存购物车失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，保存购物车失败");
        }
    }

    @ApiOperation(value = "购物车列表")
    @GetMapping
    public Object findByUserId(HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            Sort sort = new Sort(Sort.Direction.DESC, StaticKeys.SORT_CREATE_TIME);
            List<CartResponseVo> cartResponseVos = new ArrayList<>();
            List<CartT> cartBeanList = cartTRepository.findByUserTId(sessionId.toString(), sort);
            for (CartT cartBean : cartBeanList) {
                ProductT productBean = productTRepository.findOneByIdAndStatus(cartBean.getProductTId(), ProductEnums.ProductStatus.ONTHSHELF.getType());
                // 如果此商品不存在跳出当前循环
                if (productBean == null) {
                    continue;
                }
                ProductSkuT productSkuBean = productSkuTRepository.findOneByIdAndStatus(cartBean.getProductSkuTId(), ProductEnums.ProductSkuStatus.ONTHESHELF.getType());
                // 如果此商品sku不存在跳出当前循环
                if (productSkuBean == null) {
                    continue;
                }
                CartResponseVo cartResponseVo = new CartResponseVo();
                cartResponseVo.setId(cartBean.getId());
                // 商品名称
                cartResponseVo.setName(productBean.getName());
                // 商品图片
                cartResponseVo.setSkuPicture(productSkuBean.getSkuPicture());
                // 商品sku信息
                // TODO
                cartResponseVo.setProductSkuName(productSkuBean.getProductSkuAttrValName());
                cartResponseVo.setProductTId(String.valueOf(productBean.getId()));
                cartResponseVo.setProductSkuTId(cartBean.getProductSkuTId());
                cartResponseVo.setQuantity(cartBean.getQuantity());
                // 单价
                cartResponseVo.setDealPrice(Double.valueOf(productSkuBean.getSalePrice()) / StaticKeys.DISCOUNT_CALCULATION + "");
                // 总价
                cartResponseVo.setTotalPrice(Double.valueOf(cartBean.getQuantity() * productSkuBean.getSalePrice()) / StaticKeys.DISCOUNT_CALCULATION);
                cartResponseVos.add(cartResponseVo);
            }
            return Response.success(cartResponseVos, StaticKeys.SUCCESS);
        } catch (Exception e) {
            log.error("获取购物车列表失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("获取购物车列表失败");
        }
    }

    @ApiOperation(value = "购物车商品+1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "购物车ID", dataType = "String", required = true),
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "long", required = true),
            @ApiImplicitParam(name = "productSkuTId", value = "商品skuID", dataType = "String", required = true)
    })
    @GetMapping(value = "/addition/{id}/{productTId}/{productSkuTId}")
    public Object additionCart(@PathVariable String id, @PathVariable long productTId, @PathVariable String productSkuTId, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            CartT cartBean = cartTRepository.findOneByIdAndUserTIdAndProductTIdAndProductSkuTId(id, sessionId.toString(), productTId, productSkuTId);
            if (cartBean != null) {
                cartBean.setQuantity(cartBean.getQuantity() + 1);
                cartTRepository.save(cartBean);
            }
            return Response.success();
        } catch (Exception e) {
            log.error("购物车商品+1失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，购物车商品+1失败");
        }
    }

    @ApiOperation(value = "购物车商品-1")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "购物车ID", dataType = "String", required = true),
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "long", required = true),
            @ApiImplicitParam(name = "productSkuTId", value = "商品skuID", dataType = "String", required = true)
    })
    @GetMapping(value = "/subtraction/{id}/{productTId}/{productSkuTId}")
    public Object subtractionCart(@PathVariable String id, @PathVariable long productTId, @PathVariable String productSkuTId, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            CartT cartBean = cartTRepository.findOneByIdAndUserTIdAndProductTIdAndProductSkuTId(id, sessionId.toString(), productTId, productSkuTId);
            if (cartBean != null) {
                if (cartBean.getQuantity() == 1) {
                    return Response.badRequest_400("商品数量不能低于1");
                }
                cartBean.setQuantity(cartBean.getQuantity() - 1);
                cartTRepository.save(cartBean);
            }
            return Response.success();
        } catch (Exception e) {
            log.error("购物车商品-1失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，购物车商品-1失败");
        }
    }

    @ApiOperation(value = "删除购物车")
    @ApiImplicitParam(name = "id", value = "购物车ID", dataType = "String", required = true)
    @DeleteMapping(value = "/{id}")
    public Object delCart(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            CartT cartBean = cartTRepository.findOneByIdAndUserTId(id, sessionId.toString());
            if (cartBean != null) {
                cartTRepository.delete(cartBean);
            }
            return Response.success();
        } catch (Exception e) {
            log.error("删除购物车失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，删除购物车失败");
        }
    }

    @ApiOperation(value = "批量删除购物车")
    @ApiImplicitParam(name = "id", value = "购物车ID，使用“,”拼接", dataType = "String", required = true)
    @DeleteMapping(value = "/batch/{id}")
    @Transactional
    public Object batchDelCart(@PathVariable String id, HttpSession session) {
        try {
            Object sessionId = session.getAttribute(StaticKeys.USER_ID);
            if (sessionId == null) {
                return Response.unauthorized_401("登录身份失效，请重新登录");
            }
            String[] ids = id.split(StaticKeys.SPLIT);
            if (ids.length > 0) {
                for (String str : ids) {
                    CartT cartBean = cartTRepository.findOneByIdAndUserTId(str, sessionId.toString());
                    if (cartBean != null) {
                        cartTRepository.delete(cartBean);
                    }
                }
            } else {
                return Response.badRequest_400("请选择购物车信息");
            }
            return Response.success();
        } catch (Exception e) {
            log.error("购物车金额计算失败：" + e.getMessage());
            e.printStackTrace();
            return Response.serverError_500("服务器错误，购物车金额计算失败");
        }
    }

}
